package com.xiaoqiang.commons.base.utils;


import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MessageDigestUtil {

    public static final String MD5 = "MD5";
    public static final String SHA = "SHA";
    public static final String SHA224 = "SHA224";
    public static final String SHA256 = "SHA256";
    public static final String SHA512 = "SHA512";


    /**
     * @param source
     * @return
     */
    public static String digest(String source) {
        return new String(digestToBytes(source));
    }

    /**
     * @param source
     * @param method
     * @return
     */
    public static String digest(String source, String method) {
        return new String(digestToBytes(source, method));
    }

    /**
     * @param source
     * @param charset
     * @return
     */
    public static String digest(String source, Charset charset) {
        return new String(digestToBytes(source, charset));
    }

    /**
     * @param source
     * @param method
     * @param charset
     * @return
     */
    public static String digest(String source, String method, Charset charset) {
        return new String(digestToBytes(source, method, charset));
    }

    /**
     * @param source
     * @return
     */
    public static byte[] digestToBytes(String source) {
        return digestToBytes(source, StandardCharsets.UTF_8);
    }

    /**
     * @param source
     * @param method
     * @return
     */
    public static byte[] digestToBytes(String source, String method) {
        return digestToBytes(source, method, StandardCharsets.UTF_8);
    }

    /**
     * @param source
     * @param charset
     * @return
     */
    public static byte[] digestToBytes(String source, Charset charset) {
        return digestToBytes(source.getBytes(charset));
    }

    /**
     * @param source
     * @param method
     * @param charset
     * @return
     */
    public static byte[] digestToBytes(String source, String method, Charset charset) {
        return digestToBytes(source.getBytes(charset), method);
    }

    /**
     * @param source
     * @return
     */
    public static byte[] digestToBytes(byte[] source) {
        return digestToBytes(source, MD5);
    }

    /**
     * @param source
     * @param method
     * @return
     */
    public static byte[] digestToBytes(byte[] source, String method) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance(method);
            digest.update(source);
        } catch (NoSuchAlgorithmException ignored) {

        }
        return digest.digest();
    }
}
